package com.bootdo;

import org.apache.pdfbox.multipdf.Splitter;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.text.PDFTextStripper;

import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.util.List;

public class Test {
    /**
     * 第一版
     * 只是转换文字
     */
    @org.junit.Test
    public void pdfToWordOfText(){
        try {
            //pdf文件路径
            String filePath = "D:\\document\\1111.pdf";
            File fdf = new File(filePath);
            //生成的word的文件路径
            String wordPath = "D:\\document\\1111.doc";
            //通过文件名加载文档
            PDDocument doc = PDDocument.load(fdf);
            //获取文档的页数
            int pageNumber = doc.getNumberOfPages();
            //剥离器（读取pdf文件）
            PDFTextStripper stripper = new PDFTextStripper();
            //排序
            stripper.setSortByPosition(true);
            //设置要读取的起始页码
            stripper.setStartPage(1);
            //设置要读取的结束页码
            stripper.setEndPage(pageNumber);
            File word = new File(wordPath);
            if(!word.exists()){
                word.createNewFile();
            }
            //文件输出流
            FileOutputStream fos = new FileOutputStream(word);
            //
            Writer writer = new OutputStreamWriter(fos, "utf-8");
            stripper.writeText(doc, writer);
            writer.close();
            fos.close();
            System.out.println("转码完成");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    /**
     * 拆分pdf文件
     */
    public void pdfOfSplit(){
        String resourcePath = "C:/Users/Administrator/Desktop/测试.pdf";
        File resource = new File(resourcePath);
        try {
            //加载文档
            PDDocument doc = PDDocument.load(resource);
            //分割操作
            Splitter split = new Splitter ();
            //设置从那页开始分割
            split.setStartPage(1);
            //设置每个文件多少页
            split.setSplitAtPage(200);
            //分割文档
            List<PDDocument> docs = split.split(doc);
            int i =1;
            //生成分割文档
            for(PDDocument document:docs){
                String fileName = "C:/Users/Administrator/Desktop/测试"+i+".pdf";
                File file = new File(fileName);
                if(!file.exists()){
                    file.createNewFile();
                }
                FileOutputStream fos = new FileOutputStream(file);
                document.save(fos);
                document.close();
                i++;

            }
            doc.close();

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
